const stringRandom = require('string-random');
const mysql = require("./mysql/mysql.js")
const redisDao = require("./redisDao.js")
const utils = require("./utils.js")
const uuid = require("uuid")
var pageNum = 11
var local = {}
var mysqlDao = function() {
	this.db = mysql.init()
	this.redisDao = redisDao
}
//获取总页数
mysqlDao.prototype.getStatementPage = function(data,cb) {
	var self = this
	var pageSize = data.pageSize
	var pageCurrent = data.pageCurrent
	var arr = local.getStatementArr(data)
	var info = local.getSQL("statement",arr,pageSize,pageCurrent,"id")
	var sql1 = info.sql1
	var args1 = info.args1
	var info = {}
	self.db.query(sql1,args1,function(err,total) {
		info.total = JSON.parse(JSON.stringify(total))[0]["count(*)"]
		cb(true,info)
	})
}
//获取对账单
mysqlDao.prototype.getStatement = function(data,cb) {
	var self = this
	var pageSize = data.pageSize
	var pageCurrent = data.pageCurrent
	var arr = local.getStatementArr(data)
	var info = local.getSQL("statement",arr,pageSize,pageCurrent,"id")
	var sql2 = info.sql2
	var args2 = info.args2
	var info = {}
	self.db.query(sql2,args2, function(err, list) {
		if (err) {
			cb(false,{err:err})
			return
		}
		info.list = JSON.parse(JSON.stringify(list))
		cb(true,info)
	})
}
//添加对账单
mysqlDao.prototype.addStatement  = function(data,cb) {
	var self = this
	var sql = 'insert into statement SET ?'
	var info = {
		uid : data.uid,
		publisher : data.publisher,
		edition : data.edition,
		rmb : data.rmb,
		voucher : data.voucher,
		test : data.test,
		tip : data.tip,
		rate : data.rate,
		money : data.money,
		state : 0,
		create_time : data.create_time
	}
	self.redisDao.db.hincrby("statementTotal:"+info.edition,"rmb",info.rmb)
	self.redisDao.db.hincrby("statementTotal:"+info.edition,"voucher",info.voucher)
	self.redisDao.db.hincrby("statementTotal:"+info.edition,"test",info.test)
	self.redisDao.db.hincrby("statementTotal:"+info.edition,"all",info.money)
	self.db.query(sql,info, function(err, res) {
		if (err) {
			cb(false,{err:err})
		}else{
			cb(true)
		}
	})
}
//对账单回款
mysqlDao.prototype.finishStatement = function(data,cb) {
	var self = this
	var id = data.id
	var end_time = data.end_time
	self.db.query("select * from statement where id = ?",[id],function(err,list) {
		var info = JSON.parse(JSON.stringify(list[0]))
		if(err || !info){
			cb(false,{err : "对账单不存在"})
			return
		}
		if(info.state !== 0){
			cb(false,{err : "对账单已回款"})
			return
		}
		//回款统计
		self.redisDao.db.hincrby("statementTotal:"+info.edition,"money",info.money)
		var sql = "update statement SET state=?,end_time=? where id=?"
		var args = [1,end_time,id];
		self.db.query(sql,args, function(err, res) {
			if (err) {
				cb(false,{err:err})
			}else{
				cb(true)
			}
		})
	})
}
//对账单作废
mysqlDao.prototype.repealStatement = function(data,cb) {
	var self = this
	var id = data.id
	self.db.query("select * from statement where id = ?",[id],function(err,list) {
		var info = JSON.parse(JSON.stringify(list[0]))
		if(err || !info){
			cb(false,{err : "对账单不存在"})
			return
		}
		if(info.state == 2){
			cb(false,{err : "对账单已作废"})
			return
		}
		if(info.state == 1){
			//撤销回款
			self.redisDao.db.hincrby("statementTotal:"+info.edition,"money",-info.money)
		}
		self.redisDao.db.hincrby("statementTotal:"+info.edition,"rmb",-info.rmb)
		self.redisDao.db.hincrby("statementTotal:"+info.edition,"voucher",-info.voucher)
		self.redisDao.db.hincrby("statementTotal:"+info.edition,"test",-info.test)
		self.redisDao.db.hincrby("statementTotal:"+info.edition,"all",-info.money)
		var sql = "update statement SET state=? where id=?"
		var args = [2,id];
		self.db.query(sql,args, function(err, list) {
			if (err) {
				cb(false,{err:err})
			}else{
				cb(true)
			}
		})
	})
}
//获取统计数据
mysqlDao.prototype.getStatementStat = function(data,cb) {
	var beginTime = data.beginTime
	var endTime = data.endTime
	var sql = "select * from statement where state != 2 and ((create_time > ? and create_time < ?) or (end_time > ? and end_time < ?))"
	var args = [beginTime,endTime,beginTime,endTime]
	this.db.query(sql,args, function(err, list) {
		if (err) {
			console.error('addDaylyData! ' + err.stack);
			cb(false,{err:err})
		}else{
			var info = {}
			for(var i = 0;i < list.length;i++){
				list[i] = JSON.parse(JSON.stringify(list[i]))
				list[i]["create_time"] = Number(list[i]["create_time"])
				list[i]["end_time"] = Number(list[i]["end_time"])
				var key1 = utils.getMonth(list[i]["create_time"])
				if(!info[key1]){
					info[key1] = {"kaipiao":0,"benyue":0,"huikuan":0}
				}
				info[key1]["kaipiao"] += list[i]["money"]
				if(list[i]["state"] == 1){
					info[key1]["benyue"] += list[i]["money"]
					var key2 = utils.getMonth(list[i]["end_time"])
					if(!info[key2]){
						info[key2] = {"kaipiao":0,"benyue":0,"huikuan":0}
					}
					info[key2]["huikuan"] += list[i]["money"]
				}
			}
			cb(true,info)
		}
	})
}
//数据校正
mysqlDao.prototype.correctionStatementStat = function(cb) {
	var self = this
	this.getStatement({},function(flag,data) {
		var list = data.list
		var editions = {}
		for(var i = 0;i < list.length;i++){
			if(!editions[list[i].edition])
				editions[list[i].edition] = {"rmb":0,"voucher":0,"test":0,"all":0,"money":0}
			editions[list[i].edition].rmb += list[i].rmb
			editions[list[i].edition].voucher += list[i].voucher
			editions[list[i].edition].test += list[i].test
			editions[list[i].edition].all += list[i].money
			if(list[i].state == 1)
				editions[list[i].edition].money += list[i].money
		}
		for(var i in editions){
			self.redisDao.db.hmset("statementTotal:"+i,editions[i])
		}
		cb(true)
	})
}
//获取月对账单数据
mysqlDao.prototype.getStatementData = function(data,cb) {
	this.getStatement(data,function(flag,list) {
		console.log(flag,list)
		cb(flag,list)
	})
}
//获取版本对账单数据
//修改数据
//获取参数列表
local.getStatementArr = function(data) {
	var arr = []
	if(data.uid)
		arr.push({key : "uid",value : data.uid})
	if(data.edition)
		arr.push({key : "edition",value : data.edition})
	if(data.publisher)
		arr.push({key : "publisher",value : data.publisher})
	if(data.c_beginTime)
		arr.push({key : "create_time",value : data.c_beginTime,type:"more"})
	if(data.c_endTime)
		arr.push({key : "create_time",value : data.c_endTime,type:"less"})
	if(data.e_beginTime)
		arr.push({key : "end_time",value : data.e_beginTime,type:"more"})
	if(data.e_endTime)
		arr.push({key : "end_time",value : data.e_endTime,type:"less"})
	if(data.state !== undefined)
		arr.push({key : "state",value : data.state})
	return arr
}
local.getSQL = function(tableName,arr,pageSize,pageCurrent,key) {
	var sql1 = "select count(*) from " + tableName
	var sql2 = "select * from " + tableName
	var args1 = []
	var args2 = []
	for(var i = 0;i < arr.length;i++){
		var sign = "="
		switch(arr[i]["type"]){
			case "more":
				sign = ">"
			break
			case "less":
				sign = "<"
			break
			default:
				sign = "="
		}
		if(i == 0){
			sql1 += " where "
			sql2 += " where "
		}else{
			sql1 += " and "
			sql2 += " and "
		}
		sql1 += arr[i]["key"]+" "+sign+" ?"
		sql2 += arr[i]["key"]+" "+sign+" ?"
		args1.push(arr[i]["value"])
		args2.push(arr[i]["value"])
	}
	sql2 += " order by "+key
	if(pageSize && pageCurrent){
		sql2 += " desc LIMIT ?,"+pageSize
		args2.push((pageCurrent-1)*pageSize)
	}
	return {sql1:sql1,sql2:sql2,args1:args1,args2:args2}
}
module.exports = new mysqlDao()